package p.ithorns.framework.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import p.ithorns.framework.core.constants.FileConsts;
import p.ithorns.framework.core.model.ZipTreeNode;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Consumer;
import java.util.zip.*;

/**
 * ZipUtil
 * <p>
 * LZO压缩工具
 *
 * @author ithorns
 * @version 1.0
 * @date 2020/4/19 15:02
 */
public class ZipUtil {

    private final static Logger log = LoggerFactory.getLogger(ZipUtil.class);


    public static byte[] zipString(byte[] src) {
        try (
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                GZIPOutputStream gos = new GZIPOutputStream(out);
        ) {
            gos.write(src);
            gos.flush();
            gos.close();
            return out.toByteArray();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public static String unzipString(byte[] src) {
        int bufferSize = 2048;
        try (
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ByteArrayInputStream in = new ByteArrayInputStream(src);
                GZIPInputStream ginzip = new GZIPInputStream(in, bufferSize);
        ) {
            byte[] buffer = new byte[bufferSize];
            int offset = -1;
            while ((offset = ginzip.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            out.flush();
            out.close();
            return out.toString();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 缓冲大小
     */
    private final static int BUFFER_SIZE = 4096;


    /**
     * 压缩成ZIP
     *
     * @param src  -压缩文件夹路径
     * @param dest -压缩文件输出路径
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZipFile(String src, String dest) {
        // 检查文件名称，如果包含[中文字符]，则将charset设置为GBK
        Charset charset = StandardCharsets.UTF_8;
        if (StringUtil.isContainChinese(src)) {
            charset = Charset.forName("GBK");
        }
        long start = System.currentTimeMillis();
        try (
                OutputStream os = new FileOutputStream(new File(dest));
                ZipOutputStream zos = new ZipOutputStream(os, charset);
        ) {
            File sourceFile = new File(src);
            compress(sourceFile, zos, sourceFile.getName(), true);
            long end = System.currentTimeMillis();
            log.info("Compression complete, dest: {}, cost: {}", dest, (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("Zip error.", e);
        }
    }

    /**
     * 输出流
     *
     * @param src -源
     * @return ByteArrayOutputStream
     */
    public static ByteArrayOutputStream toZipStream(String src) {
        // 检查文件名称，如果包含[中文字符]，则将charset设置为GBK
        Charset charset = StandardCharsets.UTF_8;
        if (StringUtil.isContainChinese(src)) {
            charset = Charset.forName("GBK");
        }
        long start = System.currentTimeMillis();
        try (
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ZipOutputStream zos = new ZipOutputStream(os, charset);
        ) {
            File sourceFile = new File(src);
            compress(sourceFile, zos, sourceFile.getName(), true);
            long end = System.currentTimeMillis();
            log.info("Compression complete, cost: {}", (end - start) + " ms");
            return os;
        } catch (Exception e) {
            throw new RuntimeException("Zip error.", e);
        }
    }

    /**
     * 递归压缩方法
     *
     * @param sourceFile   源文件
     * @param zos          zip输出流
     * @param name         压缩后的名称
     * @param keepStucture 是否保留原来的目录结构
     *                     -true:保留目录结构;
     *                     -false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception -
     */
    private static void compress(File sourceFile,
                                 ZipOutputStream zos,
                                 String name,
                                 boolean keepStucture) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];

        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            try (FileInputStream in = new FileInputStream(sourceFile);) {
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                // Complete the entry
                zos.closeEntry();
            }
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (keepStucture) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件，不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (keepStucture) {
                        // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), keepStucture);
                    } else {
                        compress(file, zos, file.getName(), keepStucture);
                    }
                }
            }
        }
    }


    /**
     * 解压zip文件到指定目录
     *
     * @param zip  -压缩包
     * @param dest -目标数据
     */
    public static void readZip(String zip, String dest) {
        try (
                FileInputStream fis = new FileInputStream(zip);
                ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis))
        ) {
            // 从ZipInputStream读取每个条目，直到没有
            // 发现更多条目，返回值为空
            // getNextEntry()方法。
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                // 跳过文件夹
                if (entry.isDirectory()) {
                    continue;
                }
                // log.info("UnZip: {}", entry.getName());
                File file = new File(dest + File.separator + entry.getName());

                // 父级目录还没有，得先创建
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }

                int size;
                byte[] buffer = new byte[BUFFER_SIZE];
                try (
                        FileOutputStream fos = new FileOutputStream(file);
                        BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length)
                ) {
                    while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                        bos.write(buffer, 0, size);
                    }
                    bos.flush();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 构建zip节点树
     *
     * @param zipFile -
     * @return ZipTreeNode root
     */
    public static ZipTreeNode buildZipTree(ZipFile zipFile) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        Map<String, ZipTreeNode> nodes = new HashMap<>();
        ZipTreeNode root = new ZipTreeNode(zipFile.getName(), null, true);
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();
            // 排除 __MACOSX 开头的条目
            if (isMacOsFile(entryName)) {
                continue;
            }
            String[] parts = entryName.split(FileConsts.PATH_SYMBOL);
            ZipTreeNode currentNode = root;
            for (int i = 0; i < parts.length; i++) {
                String part = parts[i];

                // 排除 __MACOSX 开头 或者 空的 条目
                if (isMacOsFile(part) || part.isEmpty()) {
                    continue;
                }

                String pathSoFar = String.join(FileConsts.PATH_SYMBOL, Arrays.copyOf(parts, i + 1));
                ZipTreeNode nextNode = nodes.get(pathSoFar);
                if (nextNode == null) {
                    boolean isDirectory = i != parts.length - 1 || entry.isDirectory();
                    nextNode = new ZipTreeNode(part, entry, isDirectory);
                    nodes.put(pathSoFar, nextNode);
                    currentNode.getChildren().add(nextNode);
                }
                currentNode = nextNode;
            }
        }

        return root;
    }

    /**
     * 遍历zip树
     */
    public static void traverseZipTree(final ZipTreeNode node,
                                       final Path path,
                                       final Consumer<ZipTreeNode> consumer) {
        // 构建当前节点的完整路径
        Path fullPath = path.resolve(node.getName());
        node.setFullPath(fullPath);
        // 遍历节点直接操作
        consumer.accept(node);
        if (node.isDirectory()) {
            List<ZipTreeNode> children = node.getChildren();
            if (null != children) {
                for (ZipTreeNode child : children) {
                    traverseZipTree(child, fullPath, consumer);
                }
            }
        }
    }

    /**
     * 检测是否包含MacOs压缩文件
     */
    private static boolean isMacOsFile(String fileName) {
        return fileName.startsWith("__MACOSX") || fileName.startsWith(".");
    }

}